package interview.customContainer;

import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 面试题：写一个固定容量同步容器，拥有put和get方法，
 * 能够支持2个生产者线程以及10个消费者线程的阻塞调用
 *
 * @author: 李德才
 * @description:
 * @create: 2020-12-12 21:01
 **/
public class customContainer1<T> {

    final private LinkedList<T> lists = new LinkedList<>();
    final private int MAX = 10; //最多10个元素
    private int count = 0;

    private Lock lock = new ReentrantLock();
    /**
     * Condition 的本质就是一个等待队列
     * 一个 Condition 就是一个等待队列
     * 所以这样使用可以一起唤醒一批线程,或者说一起唤醒某一种线程
     */
    private Condition producer = lock.newCondition();
    private Condition consumer = lock.newCondition();

    public void put(T t) {
        try {
            lock.lock();
            /**
             * 这里使用 while 而不使用 if 的原因是:
             * 当线程被唤醒,if 不会再次判断  lists.size() == MAX
             * 如果被唤醒的时候刚刚好满足  lists.size() == MAX
             * 那么这里会出现问题
             * 而使用 while 则会在次判断 lists.size() == MAX
             */
            while (lists.size() == MAX) {
                producer.await();
            }
            lists.add(t);
            ++count;
            consumer.signalAll(); //通知消费者线程进行消费
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public T get() {
        T t = null;
        try {
            lock.lock();
            while (lists.size() == 0) {
                consumer.await();
            }
            t = lists.removeFirst();
            System.err.println("剩余：" + count);
            count--;
            producer.signalAll(); //通知生产者进行生产
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return t;
    }

    public static void main(String[] args) {
        customContainer1<String> customContainer1 = new customContainer1<>();
        //启动消费者线程
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                for (int j = 0; j < 5; j++) {
                    System.out.println(customContainer1.get());
                }
            }, "c" + i).start();
        }

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //启动生产者线程
        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                for (int j = 0; j < 25; j++) {
                    customContainer1.put(Thread.currentThread().getName() + " " + j);
                }
            }, "p" + i).start();
        }
    }

}
